<template>
  <div class="change-password-container">
    <el-card class="password-card">
      <!-- 使用面包屑进行组织参考csdn -->
      <el-breadcrumb
        separator-class="el-icon-arrow-right"
        style="margin: 20px 0px 30px 0px"
      >
        <!-- 路由地址的跳转 -->
        <el-breadcrumb-item
          :to="{ path: '/accountInformation/account-setting' }"
          >账号设置</el-breadcrumb-item
        >
        <el-breadcrumb-item>修改密码</el-breadcrumb-item>
      </el-breadcrumb>
      <!-- 要加上ref后面重置是才能通过ref拿到 -->
      <el-form
        :model="passwordForm"
        label-width="120px"
        class="password-change-form"
        label-position="left"
        :rules="passwordFormRules"
        ref="passwordForm"
      >
        <el-row>
          <el-col :span="18" :offset="1">
            <el-form-item label="输入旧密码" prop="oldPassword">
              <el-input
                v-model="passwordForm.oldPassword"
                spellcheck="false"
                show-password
                placeholder="请输入旧密码"
              ></el-input>
            </el-form-item>
          </el-col>
        </el-row>

        <el-row type="flex" align="middle">
          <el-col :span="18" :offset="1">
            <el-form-item label="输入新密码" prop="newPassword">
              <el-input
                v-model="passwordForm.newPassword"
                spellcheck="false"
                show-password
                placeholder="密码长度要求为6-20位"
                autocomplete="off"
              ></el-input>
            </el-form-item>
          </el-col>
          <!-- 密码的评分，只读属性的 -->
          <el-col :span="5">
            <el-rate
              v-model="newPasswordRate"
              show-text
              :texts="passwordRateTexts"
              :colors="passwordRateColors"
              disabled
            ></el-rate>
          </el-col>
        </el-row>
        <el-row>
          <el-col :span="18" :offset="1">
            <el-form-item label="确认新密码" prop="confirmPassword">
              <el-input
                v-model="passwordForm.confirmPassword"
                spellcheck="false"
                show-password
                placeholder="请再次输入新密码"
                autocomplete="off"
              ></el-input>
            </el-form-item>
          </el-col>
        </el-row>
        <el-row>
          <el-col :span="18" :offset="1">
            <el-form-item>
              <el-button
                type="primary"
                size="medium"
                @click="submitPasswordForm('passwordForm')"
                icon="el-icon-upload2"
                >提交</el-button
              >
              <el-button
                @click="resetPasswordForm('passwordForm')"
                size="medium"
                icon="el-icon-refresh"
                >重置</el-button
              >
            </el-form-item>
          </el-col>
        </el-row>
      </el-form>
    </el-card>
  </div>
</template>

<script lang="ts">
import { Component, Vue, Watch } from "vue-property-decorator";
// 注意导入方式
import { zxcvbn } from "@zxcvbn-ts/core";
import { changeUserPassword, getEncryptedAESKey } from "@/apis/apis";
import crypto from "@/utils/crypto";
import rsaEncrypt from "@/utils/rsaEncrypt";

@Component({
  name: "changePassWord",
})
export default class changePassWord extends Vue {
  // 还是需要进行表单校验
  passwordForm: {
    oldPassword: string;
    newPassword: string;
    confirmPassword: string;
  } = {
    oldPassword: "",
    newPassword: "",
    confirmPassword: "",
  };

  //  表单校验
  passwordFormRules = {
    oldPassword: [
      { required: true, message: "请输入旧密码", trigger: "blur" },
      {
        min: 6,
        max: 20,
        message: "长度在 6 到 20 个字符",
        trigger: "blur",
      },
    ],
    newPassword: [
      { required: true, message: "请输入新密码", trigger: "blur" },
      {
        min: 6,
        max: 20,
        message: "长度在 6 到 20 个字符",
        trigger: "blur",
      },
    ],
    confirmPassword: [
      { required: true, message: "请再次输入新密码", trigger: "blur" },
      {
        min: 6,
        max: 20,
        message: "长度在 6 到 20 个字符",
        trigger: "blur",
      },
    ],
  };
  // el-rate评分组件
  passwordRateTexts = ["很弱", "弱", "中", "较强", "强"];
  // 设置不同状态下的颜色,个数要和上面的一样
  passwordRateColors = {
    1: "#ce0202",
    2: "#fd8a8a",
    3: "#ffb74d",
    4: "#73dccd",
    5: "#41B883",
  };
  // 密码的评分
  newPasswordRate = 0;
  // 监听新密码的变化并使用zxcvbn库评分并更新评分，score是0-4，所以要加1
  @Watch("passwordForm.newPassword")
  onPasswordFormChange(val: string, oldVal: string) {
    // console.log(val, oldVal);
    this.newPasswordRate = zxcvbn(val).score + 1;
    // console.log(this.newPasswordRate);
  }
  // 两次新密码校验后再提交
  validatePassWordEqual(oldPassword: string, newPassword: string): boolean {
    return oldPassword === newPassword;
  }
  // 新旧相等判断,再提交表单
  submitPasswordForm(formName: string) {
    (this.$refs[formName] as any).validate((valid: boolean) => {
      if (valid) {
        // 先判断密码是否相等
        if (
          !this.validatePassWordEqual(
            this.passwordForm.newPassword,
            this.passwordForm.confirmPassword
          )
        ) {
          this.$message.error("两次输入的密码不一致");
          return false;
        } else {
          // 先请求后端接口获取
          getEncryptedAESKey()
            .then((res) => {              
              if (res.data.code === "200") {
                let encryptedAESKey = res.data.data;
                // 调用rsa解密
                let decryptedAESKey = rsaEncrypt.decryptKey(
                  encryptedAESKey
                ) as string;                
                // 使用aes加密
                let encryptedNewPassword = crypto.encrypt(
                  this.passwordForm.newPassword,
                  decryptedAESKey
                );
                let encryptedOldPassword = crypto.encrypt(
                  this.passwordForm.oldPassword,
                  decryptedAESKey
                );
                // 提交新的密码
                changeUserPassword(
                  encryptedOldPassword,
                  encryptedNewPassword
                )
                  .then((res) => {
                    if (res.data.code === "200") {
                      this.$message.success("修改密码成功!");
                      // !TODO:清空localsotrage和sessionStorage
                      localStorage.clear();
                      sessionStorage.removeItem("store")
                      // 重新定位到登录页面
                      this.$router.push("/login");
                    } else {
                      this.$message.error("修改密码失败!请重试！");
                    }
                  })
                  .catch((err) => {
                    console.log(err);
                    console.log("this is error from changeUserPassword");
                  });
              } else {
                this.$message.error("修改密码失败!请重试！");
              }
            })
            .catch((err) => {
              this.$message.error("error,修改密码失败!请重试！");
              console.log(err);
            });
        }
      } else {
        this.$message({
          message: "请按照表单要求进行填写",
          type: "error",
        });
        return false;
      }
    });
  }
  // 重置表单
  resetPasswordForm(formName: string) {
    (this.$refs[formName] as any).resetFields();
  }
}
</script>

<style lang="scss" scoped>
.change-password-container {
  display: flex;
  justify-content: center;
  width: 100%;
  height: 480px;
  .password-card {
    // width: 1050px;
    // height: 500px;
    width: 100%;
    height: 100%;
    .basic-info-form {
    }
  }
}
</style>